package qinyi365;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

import org.apache.log4j.Logger;


public class NewGetGeo {

	// http://maps.google.com/maps/geo?q=
	// %E4%B8%AD%E5%9B%BD%E5%8C%97%E4%BA%AC%E5%8C%97%E4%BA%AC%E5%B8%82%E6%B5%B7%E6%B7%80%E5%8C%BA,
	// %E4%B8%AD%E5%85%B3%E6%9D%91%E5%8D%97%E5%A4%A7%E8%A1%972%E5%8F%B7%E6%95%B0%E7%A0%81%E5%A4%A7%E5%8E%A6A%E5%BA%A7512%E5%AE%A4
	// &output=csv&oe=utf8\&sensor=true_or_false&key=ABQIAAAAbkihXiJATF78eFU-RLle9BSWpusdMD_WtIXFi3RkIymI4suE3BS8gkGin4ewkq0cxXN5LNXnZEGVCQ
	

	private  final static Logger logger = Logger
			.getLogger(NewGetGeo.class);

	
	public static void main(String args[])
	{
		Point point = NewGetGeo.getPoint("上海市徐汇区长桥六村30号202室");
		
		System.out.println(point.lng + ","+ point.lat);
		
		//System.out.println(new String(Base64.decode("MTIxLjQ0MzIyMzcyOTc4")));
	}
	
	public static Point getPoint(String address)
	{
		String spi = "小区,楼,街,大厦,局,弄,院,学,号,大道";
		//String spi = "小区,楼,街,大厦,局,镇,弄,院,学,号,村,大道";
			String spis[] = spi.split(",");
			for(String str:spis)
			{
				if(address.contains(str))
				{
					address = address.substring(0,address.indexOf(str) + str.length());
					break;
				}
			}
			Point point = null;
			String geo = NewGetGeo.getgeo(address);
			
			if(geo != null && geo.split(",").length == 2)
			{
			 String x=geo.split(",")[0];
			 String y=geo.split(",")[1];
			 point = getBaiDuFromGoogle(x,y);
			}
			return point;
	}
	private static Point getBaiDuFromGoogle(String x,String y)
	{
		Point point = null;
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append("http://api.map.baidu.com/ag/coord/convert?from=2&to=4");
		urlBuilder.append("&x=").append(x);
		urlBuilder.append("&y=").append(y);
		HttpURLConnection httpConnection = null;
		try {
			// 1、构造HttpURLConnection连接
			URL url = new URL(urlBuilder.toString());
			URLConnection urlConnection = url.openConnection();
			httpConnection = (HttpURLConnection) urlConnection;
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
			httpConnection.setConnectTimeout(30000);
			httpConnection.connect();
			// 2、接收响应结果
			InputStream inStream = httpConnection.getInputStream();
			String htmlContent = getContentByStream(inStream, "UTF-8");
			// 关闭流资源
			inStream.close();
			String bx = htmlContent.split("x\":\"")[1].split("\",\"y\"")[0];
			String by = htmlContent.split("y\":\"")[1].split("\"")[0];
			DecimalFormat df = new DecimalFormat("0.000000");
			point  = new Point(Double.valueOf(df.format(Double.valueOf(new String(Base64.decode(bx))))), 
					 Double.valueOf(df.format(Double.valueOf(new String(Base64.decode(by))))));
			return point;
		} catch (Exception e) {
			logger.error("===========获取经纬度信息异常！请求地址：" + urlBuilder.toString(), e);
			return null;
		} finally {
			// 关闭连接
			if (null != httpConnection) {
				httpConnection.disconnect();
			}
		}
	}
	private static String encodeURLForUTF8(String str) {
		try {
			str = java.net.URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	private static String getContentByStream(InputStream inStream, String encode)
			throws IOException {
		if (null == inStream) {
			return null;
		}
		StringBuilder content = new StringBuilder();
		// 采用指定编码格式读取流内容
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inStream, encode));
		String message = null;
		while (null != (message = reader.readLine())) {
			content.append(message);
			content.append("\r\n");
		}
		// 关闭读取器，释放资源
		reader.close();
		return (content.toString());
	}

	public static String getgeo(String address) {
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append("http://loveyao.info/earthquake/geo");
		urlBuilder.append("?address=").append(encodeURLForUTF8(address));
		HttpURLConnection httpConnection = null;
		try {
			// 1、构造HttpURLConnection连接
			URL url = new URL(urlBuilder.toString());
			URLConnection urlConnection = url.openConnection();
			httpConnection = (HttpURLConnection) urlConnection;
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
			httpConnection.setConnectTimeout(30000);
			httpConnection.connect();
			// 2、接收响应结果
			InputStream inStream = httpConnection.getInputStream();
			String htmlContent = getContentByStream(inStream, "UTF-8");
			// 关闭流资源
			inStream.close();
			return htmlContent;
		} catch (Exception e) {
			logger.error("===========获取经纬度信息异常！请求地址：" + address, e);
			return null;
		} finally {
			// 关闭连接
			if (null != httpConnection) {
				httpConnection.disconnect();
			}
		}

	}
}
